<template>
  <div class="task-detail-view">
    <TopNavigation :showOrganizationSection="false" :showTaskRoleSection="false" />
    
    <div class="container">
      <!-- 页面标题和返回按钮 -->
      <div class="page-header">
        <button class="back-btn" @click="handleBack">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="15 18 9 12 15 6"></polyline>
          </svg>
          返回任务列表
        </button>
        <h2>任务详情</h2>
      </div>
       
      <!-- 数据源信息区域 -->
      <div class="section-card">
        <h3>数据源信息</h3>
        <div v-if="searchConfig && searchConfig.dataSourceName" class="data-source-content">
          <p><strong>数据源名称：</strong>{{ searchConfig.dataSourceName }}</p>
          
          <!-- 数据源ID和创建信息 -->
          <div v-if="taskTypesData && taskTypesData.length > 0" class="data-source-meta">
            <p><strong>数据源ID：</strong>{{ taskTypesData[0].dataSourceId }}</p>
            <p><strong>创建时间：</strong>{{ formatDate(taskTypesData[0].createdAt) }}</p>
            <p><strong>更新时间：</strong>{{ formatDate(taskTypesData[0].updatedAt) }}</p>
          </div>
        </div>
        <div v-else class="no-data">暂无数据源信息</div>
      </div>
      
      <!-- 任务类型信息区域 -->
      <div class="section-card">
        <h3>任务类型信息</h3>
        <div v-if="taskTypesData && taskTypesData.length > 0" class="task-types-content">
          <div v-for="taskType in taskTypesData" :key="taskType.taskName" class="task-type-item">
            <h4>{{ taskType.taskName }}</h4>
            <div v-if="taskType.taskDescription" class="task-description" v-html="parseMarkdown(taskType.taskDescription)"></div>
            <div v-else class="no-description">暂无任务描述</div>
          </div>
        </div>
        <div v-else class="no-data">暂无任务类型信息</div>
      </div>
      
      <!-- 用户统计信息区域 -->
      <div v-if="Object.keys(userStatisticsData).length > 0" class="section-card">
        <h3>用户统计信息</h3>
        <div class="user-statistics-content">
          <!-- 统计概览 -->
          <h4>数据源统计概览</h4>
          <div class="overall-stats">
            <div class="stat-card small">
              <div class="stat-label">总用户数</div>
              <div class="stat-value">{{ userStatisticsData.totalUsers || 0 }}</div>
            </div>
            <div class="stat-card small">
              <div class="stat-label">总任务数</div>
              <div class="stat-value">{{ userStatisticsData.totalTasks || 0 }}</div>
            </div>
            <div class="stat-card small">
              <div class="stat-label">已完成任务</div>
              <div class="stat-value">{{ userStatisticsData.completedTasks || 0 }}</div>
            </div>
            <div class="stat-card small">
              <div class="stat-label">待处理任务</div>
              <div class="stat-value">{{ userStatisticsData.pendingTasks || 0 }}</div>
            </div>
            <div class="stat-card small">
              <div class="stat-label">处理中任务</div>
              <div class="stat-value">{{ userStatisticsData.processingTasks || 0 }}</div>
            </div>
          </div>
          
          <!-- 用户详细统计列表 -->
          <h4 style="margin-top: 20px;">用户详细统计</h4>
          <div class="user-stats-table">
            <table>
              <thead>
                <tr>
                  <th>用户ID</th>
                  <th>用户名</th>
                  <th>用户认证ID</th>
                  <th>总任务数</th>
                  <th>已完成任务</th>
                  <th>待处理任务</th>
                  <th>处理中任务</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="userStat in userStatisticsData.userStatistics" :key="userStat.userId">
                  <td>{{ userStat.userId }}</td>
                  <td>{{ userStat.userName }}</td>
                  <td>{{ userStat.userAuthId }}</td>
                  <td>{{ userStat.totalTasks }}</td>
                  <td>{{ userStat.completedTasks }}</td>
                  <td>{{ userStat.pendingTasks }}</td>
                  <td>{{ userStat.processingTasks }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- 统计信息展示区域 -->
      <div v-if="taskStats" class="task-stats-section">
        <h3>任务统计信息</h3>
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-label">总任务数</div>
            <div class="stat-value">{{ taskStats.totalTasks }}</div>
          </div>
          <div class="stat-card">
            <div class="stat-label">已分配任务</div>
            <div class="stat-value">{{ taskStats.assignedTasks }}</div>
          </div>
          <div class="stat-card">
            <div class="stat-label">未分配任务</div>
            <div class="stat-value">{{ taskStats.unassignedTasks }}</div>
          </div>
          <div class="stat-card">
            <div class="stat-label">分配率</div>
            <div class="stat-value">{{ taskStats.assignedRate }}%</div>
          </div>
        </div>
      </div>

      <!-- 搜索配置展示 - 分开的搜索区域 -->
      <div v-if="searchConfig && (searchConfig.dropdownFields || searchConfig.searchableFields)" class="search-config-section">
        <!-- 下拉搜索区域 -->
        <div v-if="hasDropdownFields" class="search-section">
          <h4>下拉搜索</h4>
          <div class="search-fields-container">
            <div v-for="field in dropdownFields" :key="field.name" class="search-field-item">
              <label>{{ field.label }}</label>
              <select v-model="searchFilters[field.name]" class="search-select">
                <option value="">全部</option>
                <option v-for="option in getDropdownOptions(field.name)" :key="option" :value="option">
                  {{ option }}
                </option>
              </select>
            </div>
          </div>
        </div>
        
        <!-- 文本搜索区域 -->
        <div v-if="hasTextFields" class="search-section">
          <h4>文本搜索</h4>
          <div class="search-fields-container">
            <div v-for="field in textFields" :key="field.name" class="search-field-item">
              <label>{{ field.label }}</label>
              <input type="text" v-model="searchFilters[field.name]" class="search-input-field">
            </div>
          </div>
        </div>
        
        <div class="search-actions">
          <button class="search-btn" @click="handleAdvancedSearch">搜索</button>
          <button class="reset-btn" @click="resetSearch">重置</button>
        </div>
      </div>

      <!-- 数据结果表格 -->
      <div class="data-results-section">
        <div v-if="paginatedData.length > 0" class="data-table">
          <table class="results-table">
            <thead>
              <tr>
                <th v-for="(column, index) in columns" :key="index">{{ column }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, rowIndex) in paginatedData" :key="rowIndex">
                <td v-for="(value, colIndex) in Object.values(row)" :key="colIndex">{{ value }}</td>
                <td class="action-buttons">
                  <button class="btn btn-small btn-primary" @click="showProcessStatus(row.id)">
                    流程状态
                  </button>
                  <button class="btn btn-small btn-warning" @click="showDataDetail(row.id)">
                    管理员审批
                  </button>
                  <button class="btn btn-small btn-default" @click="showHistoryLog(row.id)">
                    历史操作
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-else class="no-data">
          <p>{{ loading ? '加载中...' : '暂无数据' }}</p>
        </div>
        
        <!-- 分页控件 -->
        <div v-if="paginatedData.length > 0" class="pagination-container">
          <button class="btn btn-default" @click="handlePageChange(page - 1)" :disabled="page === 1">
            上一页
          </button>
          <span class="page-info">
            第 {{ page }} 页 / 共 {{ getTotalPages }} 页
          </span>
          <button class="btn btn-default" @click="handlePageChange(page + 1)" :disabled="page === getTotalPages">
            下一页
          </button>
          <div class="page-size-selector">
            <span>每页显示:</span>
            <select class="select" v-model="pageSize" @change="onPageSizeChange">
              <option value="5">5条</option>
              <option value="10">10条</option>
              <option value="20">20条</option>
              <option value="50">50条</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 流程状态模态框 -->
  <TaskProcessStatusModal
    :visible="processStatusModalVisible"
    :task-id="currentTaskId"
    @close="closeProcessStatusModal"
  />
  
  <!-- 查看数据模态框 -->
  <TaskDataDetailModal
    :visible="dataDetailModalVisible"
    :task-id="currentTaskId"
    @close="closeDataDetailModal"
  />
  
  <!-- 历史操作模态框 -->
  <TaskHistoryLogModal
    :visible="historyLogModalVisible"
    :task-id="currentTaskId"
    @close="closeHistoryLogModal"
  />
</template>

<script>
import { ref, onMounted, computed, markRaw } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { get } from '../utils/request';
import taskService from '../services/taskService';
import taskApprovalService from '../services/taskApprovalService';
import TopNavigation from '../components/TopNavigation.vue';
import TaskProcessStatusModal from '../components/TaskProcessStatusModal.vue';
import TaskDataDetailModal from '../components/TaskDataDetailModal.vue';
import TaskHistoryLogModal from '../components/TaskHistoryLogModal.vue';

// 引入Markdown解析库
let mdParser = null;

// 动态导入markdown-it并配置支持完整的Markdown语法
import('markdown-it').then(module => {
  mdParser = markRaw(module.default({
    html: true,        // 允许HTML标签
    linkify: true,     // 自动识别链接
    typographer: true, // 启用一些替换和引号美化
    breaks: true       // 转换换行符为<br>
  }));
});

export default {
  name: 'TaskDetailView',
  components: {
    TopNavigation,
    TaskProcessStatusModal,
    TaskDataDetailModal,
    TaskHistoryLogModal
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const taskId = route.params.id;
    const loading = ref(true);
    const searchKeyword = ref('');
    const dataResults = ref([]);
    const columns = ref([]);
    const searchConfig = ref(null);
    const searchFilters = ref({});
    
    // 分页相关状态
    const page = ref(1);
    const pageSize = ref(5);
    const totalItems = ref(0);
    const filteredData = ref([]);
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '暂无';
      try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('格式化日期时出错:', error);
        return dateString;
      }
    };
    
    // 模态框可见性状态
    const processStatusModalVisible = ref(false);
    const dataDetailModalVisible = ref(false);
    const historyLogModalVisible = ref(false);
    const currentTaskId = ref(null);
    
    // 任务类型数据
    const taskTypesData = ref(null);
    // 用户统计信息
    const userStatisticsData = ref({});
    
    // 获取搜索配置数据
    // 获取统计信息
    const taskStats = ref(null);
    const fetchTaskStats = async () => {
      try {
        // 从路由参数获取dataSourceId
        const dataSourceId = taskId; // 假设taskId实际是dataSourceId
        
        // 调用统计信息API接口 - 使用用户要求的路径
        const response = await get(`/api/new-tasks/overview/stats/${dataSourceId}`);
        
        console.log('统计信息数据:', response);
        
        if (response && response.data) {
          taskStats.value = response.data;
        } else {
          taskStats.value = null;
        }
      } catch (error) {
        console.error('获取统计信息失败:', error);
        taskStats.value = null;
      }
    };
    
    // 获取搜索配置数据
    const fetchSearchConfig = async () => {
      try {
        // 从路由参数获取dataSourceId
        const dataSourceId = taskId; // 假设taskId实际是dataSourceId
        
        // 调用API接口获取搜索配置
        const response = await taskService.getSearchConfig(dataSourceId);
        
        console.log('搜索配置数据:', response);
        
        if (response && response.data) {
          searchConfig.value = response.data;
          // 初始化搜索过滤器
          initializeSearchFilters(response.data.searchableFields);
        } else {
          searchConfig.value = null;
        }
      } catch (error) {
        console.error('获取搜索配置失败:', error);
        searchConfig.value = null;
      }
    };
    
    // 初始化搜索过滤器 - 同时包含dropdownFields和searchableFields
    const initializeSearchFilters = (searchableFields) => {
      const filters = {};
      
      // 添加文本搜索字段
      if (searchableFields && searchableFields.length > 0) {
        searchableFields.forEach(field => {
          filters[field.name] = '';
        });
      }
      
      // 添加下拉搜索字段
      if (searchConfig.value && searchConfig.value.dropdownFields) {
        searchConfig.value.dropdownFields.forEach(field => {
          filters[field.name] = '';
        });
      }
      
      searchFilters.value = filters;
    };
    
    // 获取下拉选项
    const getDropdownOptions = (fieldName) => {
      if (!searchConfig.value || !searchConfig.value.dropdownFields) {
        return [];
      }
      
      const field = searchConfig.value.dropdownFields.find(f => f.name === fieldName);
      return field ? field.options : [];
    };
    
    // 获取任务详情
    const fetchTaskDetail = async () => {
      try {
        loading.value = true;
        
        // 从路由参数获取dataSourceId
        const dataSourceId = taskId; // 假设taskId实际是dataSourceId
        
        // 调用API接口获取任务详情列表
        const response = await taskService.getTaskDetails(dataSourceId, 0, 100); // 获取前100条记录
        
        console.log('API响应数据:', response);
        
        if (response && response.data && response.data.length > 0) {
          // 设置数据结果，传递完整的 displayData 信息
          loadDataFromResponse(response.data);
        } else {
          // 如果没有数据，清空数据集合
          dataResults.value = [];
          filteredData.value = [];
          totalItems.value = 0;
          columns.value = [];
        }
      } catch (error) {
        console.error('获取任务详情失败:', error);
        
        // 清空数据集合，不显示模拟数据
        dataResults.value = [];
        filteredData.value = [];
        totalItems.value = 0;
        columns.value = [];
      } finally {
        loading.value = false;
      }
    };
    
    // 从 API 响应加载数据
    const loadDataFromResponse = (taskDetailsList) => {
      if (!taskDetailsList || taskDetailsList.length === 0) {
        dataResults.value = [];
        filteredData.value = [];
        totalItems.value = 0;
        columns.value = [];
        return;
      }
      
      console.log('开始处理任务详情数据:', taskDetailsList);
      
      // 转换数据时保留id字段
      const transformedData = taskDetailsList.map((taskDetail) => {
        const displayData = taskDetail.displayData || {};
        // 确保每个数据项都有id字段
        // 尝试从不同位置获取id
        const taskId = taskDetail.id || 
                       taskDetail.taskId || 
                       taskDetail.task_id || 
                       displayData.id || 
                       `task_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
        
        return {
          ...displayData,
          id: taskId // 添加id字段，确保每个数据项都有唯一标识
        };
      });
      
      dataResults.value = transformedData;
      filteredData.value = [...transformedData];
      totalItems.value = transformedData.length;
      page.value = 1; // 重置到第一页
      
      if (transformedData.length > 0) {
        const firstRow = transformedData[0];
        const allKeys = Object.keys(firstRow);
        columns.value = [...allKeys];
        columns.value.push('操作');
      }
      
      console.log('数据加载完成，总记录数:', totalItems.value);
      console.log('最终表格数据:', transformedData);
    };
    
    // 显示流程状态模态框
    const showProcessStatus = (taskId) => {
      // 检查taskId是否有效
      if (!taskId || taskId === 'undefined' || taskId === null) {
        console.warn('无效的taskId，不打开流程状态模态框');
        return;
      }
      console.log('显示流程状态，taskId:', taskId);
      // 确保taskId为字符串类型
      currentTaskId.value = String(taskId);
      processStatusModalVisible.value = true;
    };
    
    // 显示查看数据模态框
    const showDataDetail = (taskId) => {
      // 检查taskId是否有效
      if (!taskId || taskId === 'undefined' || taskId === null) {
        console.warn('无效的taskId，不打开查看数据模态框');
        return;
      }
      // 确保taskId为字符串类型
      currentTaskId.value = String(taskId);
      dataDetailModalVisible.value = true;
    };
    
    // 显示历史操作模态框
    const showHistoryLog = (taskId) => {
      // 检查taskId是否有效
      if (!taskId || taskId === 'undefined' || taskId === null) {
        console.warn('无效的taskId，不打开历史操作模态框');
        return;
      }
      // 确保taskId为字符串类型
      currentTaskId.value = String(taskId);
      historyLogModalVisible.value = true;
    };
    
    // 关闭流程状态模态框
    const closeProcessStatusModal = () => {
      processStatusModalVisible.value = false;
    };
    
    // 关闭查看数据模态框
    const closeDataDetailModal = () => {
      dataDetailModalVisible.value = false;
    };
    
    // 关闭历史操作模态框
    const closeHistoryLogModal = () => {
      historyLogModalVisible.value = false;
    };
    
    // 计算分页数据
    const paginatedData = computed(() => {
      const start = (page.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredData.value.slice(start, end);
    });
    
    // 获取总页数
    const getTotalPages = computed(() => {
      return Math.ceil(totalItems.value / pageSize.value);
    });
    
    // 处理页码变化
    const handlePageChange = (newPage) => {
      if (newPage >= 1 && newPage <= getTotalPages.value) {
        page.value = newPage;
        // 滚动到表格顶部
        const tableContainer = document.querySelector('.data-results-section');
        if (tableContainer) {
          tableContainer.scrollTop = 0;
        }
      }
    };
    
    // 处理每页显示数量变化
    const onPageSizeChange = () => {
      page.value = 1; // 重置到第一页
    };
    
    // 处理数据搜索
    const handleSearchData = () => {
      if (!searchKeyword.value.trim()) {
        filteredData.value = [...dataResults.value];
        totalItems.value = dataResults.value.length;
      } else {
        // 搜索逻辑 - 支持在所有字段中搜索
        const keyword = searchKeyword.value.toLowerCase();
        filteredData.value = dataResults.value.filter(item => {
          return Object.values(item).some(value => {
            if (value === null || value === undefined) return false;
            return String(value).toLowerCase().includes(keyword);
          });
        });
        totalItems.value = filteredData.value.length;
      }
      page.value = 1; // 重置到第一页
    };
    
    // 处理高级搜索
    const handleAdvancedSearch = async () => {
      // 设置加载状态
      loading.value = true;
      
      try {
        // 从路由参数获取dataSourceId
        const dataSourceId = taskId; // 假设taskId实际是dataSourceId
        
        // 构建searchParams对象，只包含有值的搜索字段
        const searchParams = {};
        Object.keys(searchFilters.value).forEach(fieldName => {
          const filterValue = searchFilters.value[fieldName];
          // 只添加有值的搜索字段
          if (filterValue && filterValue !== '') {
            searchParams[fieldName] = filterValue;
          }
        });
        
        // 构建请求数据
        const requestData = {
          dataSourceId: parseInt(dataSourceId),
          searchParams: searchParams
        };
        
        console.log('搜索请求数据:', requestData);
        
        // 调用searchNewTasks接口
        const response = await taskApprovalService.searchNewTasks(requestData);
        
        console.log('搜索响应数据:', response);
        
        if (response && response.data && response.data.length > 0) {
          // 加载搜索结果数据
          loadDataFromResponse(response.data);
        } else {
          // 如果没有搜索结果，清空数据集合
          dataResults.value = [];
          filteredData.value = [];
          totalItems.value = 0;
          columns.value = [];
        }
      } catch (error) {
        console.error('搜索任务失败:', error);
        // 清空数据集合
        dataResults.value = [];
        filteredData.value = [];
        totalItems.value = 0;
        columns.value = [];
      } finally {
        loading.value = false;
      }
    };
    
    // 重置搜索
    const resetSearch = () => {
      if (searchConfig.value && searchConfig.value.searchableFields) {
        initializeSearchFilters(searchConfig.value.searchableFields);
      }
      // 恢复原始数据
      filteredData.value = [...dataResults.value];
      totalItems.value = dataResults.value.length;
      page.value = 1; // 重置到第一页
    };
    
    // 处理返回
    const handleBack = () => {
      router.push('/task-management');
    };

    // 获取任务类型数据
    const fetchTaskTypesData = async () => {
      try {
        // 从路由参数获取dataSourceId
        const dataSourceId = taskId; // 假设taskId实际是dataSourceId
        
        // 调用接口获取任务类型数据
        const response = await taskApprovalService.getTaskTypesByDataSource(dataSourceId);
        
        console.log('任务类型数据:', response);
        
        if (response && response.data) {
          taskTypesData.value = response.data;
          // 获取用户统计信息
          await fetchUserStatisticsData(dataSourceId);
        } else {
          taskTypesData.value = null;
        }
      } catch (error) {
        console.error('获取任务类型数据失败:', error);
        taskTypesData.value = null;
      }
    };
    
    // 获取用户统计信息
    const fetchUserStatisticsData = async (dataSourceId) => {
      try {
        // 调用接口获取用户统计信息
        const response = await taskApprovalService.getUserStatisticsByDataSource(dataSourceId);
        
        console.log('用户统计信息:', response);
        
        // 确保正确处理API响应格式，根据用户要求的接口示例，数据在response.data中
        if (response && response.code === 200 && response.status === 'success' && response.data) {
          userStatisticsData.value = response.data;
          console.log('成功获取并设置用户统计数据:', userStatisticsData.value);
        } else {
          console.warn('用户统计信息响应格式不符合预期:', response);
          userStatisticsData.value = {};
        }
      } catch (error) {
        console.error('获取用户统计信息失败:', error);
        userStatisticsData.value = {};
      }
    };
    
    // 初始加载 - 同时获取任务详情、搜索配置、统计信息和任务类型数据
    onMounted(() => {
      Promise.all([fetchTaskDetail(), fetchSearchConfig(), fetchTaskStats(), fetchTaskTypesData()]);
    });
    
    // 计算属性：获取下拉搜索字段 - 直接使用API返回的dropdownFields
    const dropdownFields = computed(() => {
      if (!searchConfig.value || !searchConfig.value.dropdownFields) {
        return [];
      }
      return searchConfig.value.dropdownFields;
    });
    
    // 计算属性：获取文本搜索字段 - 使用API返回的searchableFields
    const textFields = computed(() => {
      if (!searchConfig.value || !searchConfig.value.searchableFields) {
        return [];
      }
      return searchConfig.value.searchableFields;
    });
    
    // 计算属性：是否有下拉搜索字段
    const hasDropdownFields = computed(() => {
      return dropdownFields.value.length > 0;
    });
    
    // 计算属性：是否有文本搜索字段
    const hasTextFields = computed(() => {
      return textFields.value.length > 0;
    });
    
    // 解析 Markdown 内容
    const parseMarkdown = (markdown) => {
      if (!markdown || !mdParser) {
        return markdown || '';
      }
      try {
        // 预处理Markdown内容，确保标题#后面有空格（支持所有级别标题：#到######）
        let processedMarkdown = markdown.replace(/(^|\n)(#{1,6})(\S)/g, '$1$2 $3');
        
        // 调用配置好的markdown-it进行完整解析
        const result = mdParser.render(processedMarkdown);
        
        // 为解析结果添加统一的样式类，并去掉标题前的#符号
        // 注意：这里通过正则表达式处理HTML结果，移除标题标签内的#符号
        // 使用markdown-content类以支持列表缩进样式
        const styledResult = `<div class="markdown-content">${result.replace(/<(h[1-6])>(\s*#{1,6}\s*)(.*?)<\/\1>/g, '<$1>$3</$1>')}</div>`;
        
        return styledResult;
      } catch (error) {
        console.error('Markdown解析错误:', error);
        // 出错时返回原始文本，但添加基本样式
        return `<div class="markdown-content">${markdown}</div>`;
      }
    };
    
    // 格式化统计信息的键名
    const formatStatKey = (key) => {
      const keyMap = {
        totalUsers: '总用户数',
        totalTasks: '总任务数',
        completedTasks: '已完成任务',
        pendingTasks: '待处理任务',
        processingTasks: '处理中任务',
        userId: '用户ID',
        userName: '用户名',
        userAuthId: '用户认证ID'
      };
      return keyMap[key] || key;
    };
    
    return {
      loading,
      searchKeyword,
      dataResults,
      filteredData,
      paginatedData,
      columns,
      page,
      pageSize,
      totalItems,
      getTotalPages,
      fetchTaskDetail,
      loadDataFromResponse,
      handleSearchData,
      handleBack,
      handlePageChange,
      onPageSizeChange,
      formatDate,
      taskTypesData,
      parseMarkdown,
      processStatusModalVisible,
      dataDetailModalVisible,
      historyLogModalVisible,
      currentTaskId,
      showProcessStatus,
      showDataDetail,
      showHistoryLog,
      closeProcessStatusModal,
      closeDataDetailModal,
      closeHistoryLogModal,
      searchConfig,
      searchFilters,
      getDropdownOptions,
      handleAdvancedSearch,
      resetSearch,
      dropdownFields,
      textFields,
      hasDropdownFields,
      hasTextFields,
      taskStats,
      fetchTaskStats,
      userStatisticsData,
      formatStatKey
    };
  }
};
</script>

<style scoped>
.task-detail-view {
  background-color: var(--bg-light);
  min-height: 100vh;
  width: 100%;
  overflow-y: auto;
}

/* 全局滚动条样式 */
.task-detail-view::-webkit-scrollbar {
  width: 8px;
}

.task-detail-view::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.task-detail-view::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.task-detail-view::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.container {
  padding: 10px 20px 20px 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid var(--border-color);
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 12px;
  background-color: var(--bg-white);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: var(--text-primary);
  transition: all 0.2s ease;
}

.back-btn:hover {
  background-color: var(--bg-hover);
  border-color: var(--primary-color);
}

.page-header h2 {
  margin-left: 20px;
  font-size: 18px;
  font-weight: 500;
  color: var(--text-primary);
}

/* 数据源信息样式 */
/* 通用分区卡片样式 */
      .section-card {
        margin-bottom: 24px;
        padding: 20px;
        background-color: #ffffff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        border: 1px solid var(--border-light);
      }
      
      .section-card h3 {
        margin-top: 0;
        margin-bottom: 16px;
        font-size: 18px;
        font-weight: 600;
        color: #333;
        padding-bottom: 12px;
        border-bottom: 2px solid var(--border-base);
      }
      
      /* 数据源内容样式 */
      .data-source-content p {
        margin: 8px 0;
        color: #555;
      }
      
      .data-source-meta {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid var(--border-light);
      }
      
      .data-source-meta p {
        margin: 6px 0;
        font-size: 14px;
        color: #666;
      }
      
      /* 任务类型内容样式 */
      .task-types-content {
        margin-top: 8px;
      }
      
      .task-type-item {
        margin-bottom: 20px;
        padding: 16px;
        background-color: #f8f9fa;
        border-radius: 6px;
        border-left: 4px solid var(--primary-color);
      }
      
      .task-type-item:last-child {
        margin-bottom: 0;
      }
      
      .task-type-item h4 {
        margin-top: 0;
        margin-bottom: 12px;
        font-size: 16px;
        color: #333;
      }
      
      .no-description {
        color: #999;
        font-style: italic;
        text-align: center;
        padding: 10px;
      }
      
      /* 用户统计内容样式 */
      .user-statistics-content {
        margin-top: 8px;
      }
      
      .user-statistics-content h4 {
        margin-top: 0;
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

/* Markdown 内容样式 */
.task-description h1,
.task-description h2,
.task-description h3,
.task-description h4,
.task-description h5,
.task-description h6 {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 10px 0 5px 0;
}

.task-description p {
  margin: 5px 0;
}

.task-description ul,
.task-description ol {
  margin: 5px 0;
  padding-left: 20px;
}

.task-description code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 12px;
}

/* 任务统计信息区域样式 */
.task-stats-section {
  background-color: var(--bg-white);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.task-stats-section h3 {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.stat-card {
  background-color: var(--bg-light);
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  transition: transform 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--primary-color);
}

.data-source-info h3 {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 0;
}

/* 搜索配置区域样式 */
.search-config-section {
  background-color: var(--bg-white);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 搜索区域容器 */
.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: var(--bg-light);
  border-radius: 6px;
  border-left: 3px solid var(--primary-color);
}

/* 搜索区域标题 */
.search-section h4 {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border-color);
}

.search-fields-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.search-field-item {
  flex: 1;
  min-width: 200px;
}

.search-field-item label {
  display: block;
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 5px;
}

.search-select, .search-input-field {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
  color: var(--text-primary);
  background-color: var(--bg-white);
}

.search-select:focus, .search-input-field:focus {
  outline: none;
  border-color: var(--primary-color);
}

.search-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 15px;
  border-top: 1px solid var(--border-color);
}

.search-btn {
  padding: 8px 16px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
}

.search-btn:hover {
  background-color: var(--primary-hover);
}

.reset-btn {
  padding: 8px 16px;
  background-color: var(--bg-light);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.reset-btn:hover {
  background-color: var(--bg-hover);
}

.task-info-section {
  background-color: var(--bg-white);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.task-basic-info h3 {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 15px;
}

.task-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-row {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.form-item {
  flex: 1;
  min-width: 200px;
}

.form-item.full-width {
  flex: 100%;
  min-width: unset;
}

.form-item label {
  display: block;
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 5px;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
  color: var(--text-primary);
  background-color: var(--bg-white);
}

.form-textarea {
  resize: vertical;
  min-height: 60px;
}

.form-input:disabled,
.form-select:disabled,
.form-textarea:disabled {
  background-color: var(--bg-disabled);
  color: var(--text-disabled);
  cursor: not-allowed;
}

.status-modules {
  display: flex;
  gap: 20px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.status-module {
  flex: 1;
  text-align: center;
}

.status-module h4 {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 10px;
  font-weight: normal;
}

.status-number {
  font-size: 24px;
  font-weight: 500;
  color: var(--primary-color);
}

.search-data-section {
  background-color: var(--bg-white);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-input-wrapper {
  display: flex;
  gap: 10px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
}

.data-results-section {
  background-color: var(--bg-white);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.data-table {
  overflow-x: auto;
}

.results-table {
  width: 100%;
  border-collapse: collapse;
}

.results-table th {
  background-color: var(--bg-light);
  padding: 10px;
  text-align: left;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  border-bottom: 2px solid var(--border-color);
}

.results-table td {
  padding: 10px;
  font-size: 14px;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-color);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
}

.btn-small {
  padding: 4px 8px;
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover {
  background-color: var(--primary-hover);
}

.btn-secondary {
  background-color: var(--secondary-color);
  color: white;
}

.btn-secondary:hover {
  background-color: var(--secondary-hover);
}

.btn-default {
  background-color: var(--bg-light);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
}

.btn-default:hover {
  background-color: var(--bg-hover);
}

.btn:disabled {
  background-color: var(--bg-disabled);
  color: var(--text-disabled);
  cursor: not-allowed;
}

/* 已处理任务栏样式 */
.processed-tasks-section {
  background-color: var(--bg-white);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.processed-tasks-section h3 {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
}

.processed-tasks-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.processed-task-item {
  flex: 1;
  min-width: 280px;
  padding: 12px 16px;
  background-color: var(--bg-light);
  border-radius: 6px;
  border-left: 3px solid var(--secondary-color);
  cursor: pointer;
  transition: all 0.2s ease;
}

.processed-task-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #f5f7fa;
}

.processed-task-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.processed-task-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.processed-task-status {
  font-size: 12px;
  color: var(--secondary-color);
  background-color: rgba(90, 149, 250, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
}

.processed-task-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.no-data {
  text-align: center;
  padding: 40px;
  color: var(--text-secondary);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-selector span {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 用户统计信息样式 */
.user-statistics-info {
  margin-top: 20px;
  padding: 16px;
  background-color: var(--background-light);
  border: 1px solid var(--border-color);
  border-radius: 8px;
}

.user-statistics-info h5 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.overall-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.stat-card.small {
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 12px;
  text-align: center;
}

.stat-card.small .stat-label {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.stat-card.small .stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--primary-color);
}

/* Markdown文本样式 */
.markdown-text {
  line-height: 1.6;
  font-size: 14px;
  color: var(--text-primary);
}

.task-description h1,
.task-description h2,
.task-description h3,
.task-description h4,
.task-description h5,
.task-description h6 {
  margin-top: 16px;
  margin-bottom: 8px;
  color: var(--text-primary);
  font-weight: 600;
}

.task-description h1 {
  font-size: 24px;
  border-bottom: 1px solid var(--border-base);
  padding-bottom: 8px;
}

.task-description h2 {
  font-size: 20px;
  border-bottom: 1px solid var(--border-light);
  padding-bottom: 6px;
}

.task-description h3 {
  font-size: 18px;
}

.task-description p {
  margin-bottom: 12px;
  line-height: 1.6;
}

.task-description strong {
  font-weight: 600;
  color: var(--text-primary);
}

.task-description em {
  font-style: italic;
  color: var(--text-primary);
}

.task-description ul,
.task-description ol {
  margin-left: 24px;
  margin-bottom: 12px;
}

.task-description li {
  margin-bottom: 4px;
}

.task-description pre {
  background-color: var(--bg-light);
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 12px;
  font-family: monospace;
}

.task-description code {
  background-color: var(--bg-light);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 12px;
}

.task-description a {
  color: var(--primary-color);
  text-decoration: none;
}

.task-description a:hover {
  text-decoration: underline;
}

/* 用户统计表格样式 */
.user-stats-table {
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
}

.user-stats-table table {
  width: 100%;
  border-collapse: collapse;
}

.user-stats-table th,
.user-stats-table td {
  padding: 10px 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.user-stats-table th {
  background-color: var(--background-light);
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
}

.user-stats-table td {
  font-size: 13px;
  color: var(--text-primary);
}

.user-stats-table tr:last-child td {
  border-bottom: none;
}

.user-stats-table tr:hover {
  background-color: var(--background-hover);
}

.select {
  padding: 4px 8px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
  
  .form-row {
    flex-direction: column;
  }
  
  .form-item {
    min-width: unset;
  }
  
  .status-modules {
    flex-direction: column;
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  /* 响应式搜索配置区域 */
  .search-fields-container {
    flex-direction: column;
  }
  
  .search-field-item {
    min-width: unset;
  }
  
  .search-actions {
    justify-content: center;
  }
}
</style>